<script setup lang="ts">
import { ref, reactive, toRefs, toRef } from 'vue'

// ref 示例
const count = ref(0)
const message = ref('Hello')

// reactive 示例
const state = reactive({
  name: '张三',
  age: 25,
  address: {
    city: '北京',
    area: '朝阳区'
  }
})

// toRefs 示例：解构响应式对象，保持响应性
const { name, age } = toRefs(state)
// 现在 name.value 会同步更新 state.name

// toRef 示例：创建单个属性的引用
const city = toRef(state.address, 'city')
// 现在 city.value 会同步更新 state.address.city

// 修改数据的方法
const increment = () => {
  count.value++
}

const updateMessage = () => {
  message.value = 'Updated!'
}

const updateState = () => {
  // 通过原始对象更新
  state.age++
  state.address.city = '上海'
  
  // 通过解构的响应式引用更新
  name.value = '李四'
  
  // 通过单个属性引用更新
  city.value = '广州'
}
</script>

<template>
  <div class="reactivity-demo">
    <h2>响应式基础示例</h2>
    
    <section class="ref-demo">
      <h3>ref 示例</h3>
      <p>计数器: {{ count }}</p>
      <button @click="increment">增加</button>
      
      <p>消息: {{ message }}</p>
      <button @click="updateMessage">更新消息</button>
    </section>

    <section class="reactive-demo">
      <h3>reactive 与 toRefs/toRef 示例</h3>
      <div>
        <p>通过原始对象访问: {{ state.name }} - {{ state.age }}</p>
        <p>通过解构的响应式引用访问: {{ name }} - {{ age }}</p>
        <p>通过 toRef 访问城市: {{ city }}</p>
        <button @click="updateState">更新所有状态</button>
      </div>
    </section>
  </div>
</template>

<style scoped>
.reactivity-demo {
  padding: 20px;
}

section {
  margin: 20px 0;
  padding: 15px;
  border: 1px solid #ddd;
  border-radius: 8px;
}

button {
  margin: 5px;
  padding: 5px 15px;
}
</style> 